package com.fcat.common.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fcat.common.user.constant.UserConstant;
import com.fcat.common.user.exception.FeignRequestException;
import com.fcat.springboot.mybatis.util.JsonUtil;
import com.fcat.base.common.util.StrUtil;
import com.fcat.common.user.config.Constants;
import com.fcat.common.user.entity.*;
import com.fcat.common.user.enums.StateCode;
import com.fcat.common.user.rpc.KeycloakFeign;
import com.fcat.common.user.service.KeycloakService;
import com.fcat.common.user.slaver.mapper.KeycloakRoleMapper;
import com.fcat.common.user.slaver.mapper.PolicyConfigMapper;
import com.fcat.common.user.slaver.mapper.ResourcePolicyMapper;
import com.fcat.common.user.slaver.mapper.ResourceServerResourceMapper;
import com.fcat.common.user.util.KeycloakUtil;
import com.fcat.common.user.util.RegUtil;
import com.fcat.common.user.vo.*;
import com.fcat.springboot.redis.service.RedisService;
import com.redis.common.TokenInfo;
import feign.FeignException;
import org.keycloak.jose.jws.JWSInput;
import org.keycloak.jose.jws.JWSInputException;
import org.keycloak.representations.AccessToken;
import org.keycloak.representations.AccessTokenResponse;
import org.keycloak.representations.idm.CredentialRepresentation;
import org.keycloak.representations.idm.UserRepresentation;
import org.keycloak.util.BasicAuthHelper;
import org.keycloak.util.JsonSerialization;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;


import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

@Service
public class KeycloakServiceImpl implements KeycloakService {

    @Value("${token.clienId}")
    private String clienId;

    @Value("${token.realm}")
    private String realm;


    @Value("${token.client}")
    private String client;
    @Value("${token.clientSecret}")
    private String clientSecret;
    @Autowired
    private KeycloakFeign keycloakFeign;
    @Resource
    private KeycloakRoleMapper keycloakRoleMapper;
    @Resource
    private PolicyConfigMapper policyConfigMapper;
    @Resource
    private ResourcePolicyMapper resourcePolicyMapper;
    @Resource
    private ResourceServerResourceMapper resourceServerResourceMapper;
    @Autowired
    private RedisService redisService;



    @Override
    public JSONObject token(JSONObject jsonObject) {
        TokenQuery query=JSONObject.toJavaObject(jsonObject,TokenQuery.class);

        if (StrUtil.isEmpty(query.getRealm()) || StrUtil.isEmpty(query.getClient())
                || StrUtil.isEmpty(query.getUsername()) || StrUtil.isEmpty(query.getClientSecret())
                || (StrUtil.isEmpty(query.getIp()) && RegUtil.isIpv4(query.getIp()))) {
//            return Result.failure(StateCode.ERROR_PARAMS_WRONGFUL);
            return JsonUtil.getFailJsonObject(StateCode.ERROR_PARAMS_WRONGFUL.getMsg());
        }
        final String client = query.getClient();
        final String clientSecret = query.getClientSecret();
        final MultiValueMap<String, String> params = new LinkedMultiValueMap<>(4);
        params.add(Constants.CLIENT_ID, client);
        params.add(Constants.USERNAME, query.getUsername());
        params.add(Constants.PASSWORD, query.getPassword());
        params.add(Constants.GRANT_TYPE, Constants.PASSWORD);
        params.add(Constants.IP, query.getIp());
//        User user = new User(client, query.getUsername());
        try {
            AccessTokenResponse response = keycloakFeign.token(BasicAuthHelper.createHeader(client, clientSecret), query.getRealm(), params);
            if (response != null) {
//                insertSuccessLog(user, Constants.OPRATE_LOGIN, Module.USER.getCode(), Module.USER.getValue(), query.toString());
                String token = response.getTokenType() + " " + response.getToken();
//                if (!verify(token, query)) {
//                    return Result.failure(StateCode.ERROR_VERIFY);
//                }
                final TokenVo tokenVo = new TokenVo();
                tokenVo.setToken(token);
                tokenVo.setExpiresIn(response.getExpiresIn());
                tokenVo.setRefreshToken(response.getRefreshToken());
                tokenVo.setRefreshExpiresIn(response.getRefreshExpiresIn());
//                return Result.success(tokenVo);
                return JsonUtil.getSuccessJsonObject(token);
//                return Result.success("erewre");
            }
        }catch (FeignException fe){
            fe.printStackTrace();
//            return KeycloakUtil.getMsg(fe);
            return KeycloakUtil.getMsg(fe);
        }
        catch (Exception e) {
            return JsonUtil.getFailJsonObject(KeycloakUtil.getMsg(e));
        }
//        return Result.failure(StateCode.SYSTEM_EXCEPTION);
        return JsonUtil.getFailJsonObject(StateCode.SYSTEM_EXCEPTION.getMsg());
    }

    @Override
    public JSONObject createUser(UserCreateQuery query, String token) {
        if (StrUtil.isEmpty(query.getUsername()) || StrUtil.isEmpty(query.getPassword())) {
            return JsonUtil.getFailJsonObject(StateCode.ERROR_PARAMS_WRONGFUL.getMsg());
        }
//        if (!validateAttribute(query.getAttributes())) {
//            return JsonUtil.getFailJsonObject(StateCode.ERROR_ATTRIBUTES_INCLUDE);
//        }

        if (!StrUtil.isEmpty(query.getSex())
                && (!query.getSex().equals(Constants.MAN) && !query.getSex().equals(Constants.WOMEN))) {
                return JsonUtil.getFailJsonObject(StateCode.ERROR_PARAMS_WRONGFUL_MSG.getCode(), "性别内容错误（0：男，1：女）");
        }

//        if (!StrUtil.isEmpty(query.getIdcard()) && !IdcardUtil.validateCard(query.getIdcard())) {
//            return JsonUtil.getFailJsonObject(StateCode.ERROR_PARAMS_WRONGFUL_MSG.getCode(), "身份证格式错误");
//        }

        if (!StrUtil.isEmpty(query.getWorkNature())
                && (!query.getWorkNature().equals(Constants.XIEJING) && !query.getWorkNature().equals(Constants.MINJING))) {
            return JsonUtil.getFailJsonObject(StateCode.ERROR_PARAMS_WRONGFUL_MSG.getCode(), "警种内容错误（0协警；1民警）");
        }

        if (!StrUtil.isEmpty(query.getIsFirst())
                && (!query.getIsFirst().equals(Constants.TRUE) && !query.getIsFirst().equals(Constants.FALSE))) {
            return JsonUtil.getFailJsonObject(StateCode.ERROR_PARAMS_WRONGFUL_MSG.getCode(), "首次登录内容错误（true：是，false：否）");
        }

        final org.keycloak.representations.idm.UserRepresentation userRep = new org.keycloak.representations.idm.UserRepresentation();
        userRep.setUsername(query.getUsername());
        final CredentialRepresentation credentialRepresentation = new CredentialRepresentation();
        credentialRepresentation.setType(CredentialRepresentation.PASSWORD);
        credentialRepresentation.setValue(query.getPassword());
        credentialRepresentation.setTemporary(false);
        userRep.setCredentials(Arrays.asList(credentialRepresentation));
        if (!StrUtil.isEmpty(query.getFirstName())) {
            userRep.setFirstName(query.getFirstName());
        }
        if (!StrUtil.isEmpty(query.getLastName())) {
            userRep.setLastName(query.getLastName());
        }
        if (!StrUtil.isEmpty(query.getEmail())) {
            userRep.setEmail(query.getEmail());
        }
        userRep.setEnabled(true);
        KeycloakUser keycloakUser = null;
        try {
            keycloakUser = generateUser(token);
            keycloakFeign.createUser(token, keycloakUser.getRealm(), userRep);
        } catch (FeignException fe){
            return KeycloakUtil.getMsg(fe);
        } catch (Exception e) {
            return JsonUtil.getFailJsonObject(KeycloakUtil.getMsg(e));
        }
        return JsonUtil.getSuccessJsonObject();
    }

    @Override
    public JSONObject updatePassword(String token, String username, String password) {
        JSONObject jsonObject=getUserInfoByUsername(token,username);
        if(jsonObject.getIntValue("code")!=0){
            return jsonObject;
        }
        if(StrUtil.isBlank(jsonObject.getString("data"))){
            return JsonUtil.getFailJsonObject("该用户不存在");
        }
        KeycloakUser keycloakUser=JSON.parseObject(jsonObject.getString("data"),KeycloakUser.class);

        final CredentialRepresentation credentialRepresentation = new CredentialRepresentation();
        credentialRepresentation.setType(CredentialRepresentation.PASSWORD);
        credentialRepresentation.setValue(password);
        credentialRepresentation.setTemporary(false);

        try {
            keycloakFeign.resetPassword(token, keycloakUser.getRealm(), keycloakUser.getUserId(), credentialRepresentation);
            return JsonUtil.getSuccessJsonObject();
        }catch (FeignException fe){
            fe.printStackTrace();
            return KeycloakUtil.getMsg(fe);
        } catch (Exception e) {
            System.err.println(e.getMessage());
            System.err.println(e.toString());
            return JsonUtil.getFailJsonObject(e.getMessage());
        }
    }


    @Override
    public JSONObject logout(String token) {
        KeycloakUser keycloakUser = null;
        try {
            keycloakUser = generateUser(token);
            keycloakFeign.logout(token, keycloakUser.getRealm(), keycloakUser.getUserId());
            return JsonUtil.getSuccessJsonObject();
        } catch (Exception e) {
            return JsonUtil.getFailJsonObject(KeycloakUtil.getMsg(e));
        }
    }

    @Override
    public JSONObject invalidateToken(String token) {
        KeycloakUser user = null;
        try {
            user = generateUser(token);
            keycloakFeign.deleteSession(token, user.getRealm(), user.getSessionId());
            return JsonUtil.getSuccessJsonObject();
        }catch (FeignException fe){
            if(fe.status()==401){//401说明token无效，也算退出成功
                return JsonUtil.getSuccessJsonObject();
            }
            return KeycloakUtil.getMsg(fe);
        }catch (Exception e) {
            return JsonUtil.getFailJsonObject(KeycloakUtil.getMsg(e));
        }
    }

    @Override
    public JSONObject delUser(String token, String userId) {
        if (StrUtil.isEmpty(userId)) {
            return JsonUtil.getFailJsonObject("keycloak 用户id 不能为空");
        }
        KeycloakUser keycloakUser = null;
        try {
            keycloakUser = generateUser(token);
            keycloakFeign.deleteUser(token, keycloakUser.getRealm(), userId);
            return JsonUtil.getSuccessJsonObject();
        } catch (Exception e) {
            return JsonUtil.getFailJsonObject(e.getMessage());
        }
    }

    /**
     * 根据token 生成用户
     *
     * @param token
     * @return
     */
    public KeycloakUser generateUser(String token){
        if (StrUtil.isEmpty(token)) {
            return null;
        }
        if (token.startsWith("bearer")) {
            token = token.replace("bearer ", "");
        }
        KeycloakUser keycloakUser = null;
        try {
            AccessToken accessToken = JsonSerialization.readValue(new JWSInput(token).getContent(), AccessToken.class);
            keycloakUser = new KeycloakUser();
            keycloakUser.setUserId(accessToken.getSubject());
            keycloakUser.setClient(accessToken.getIssuedFor());
            keycloakUser.setUsername(accessToken.getPreferredUsername());
            keycloakUser.setSessionId(accessToken.getSessionState());
            keycloakUser.setToken(token);
            String issuer = accessToken.getIssuer();
            String realm = issuer.substring(issuer.lastIndexOf("/") + 1, issuer.length());
            keycloakUser.setRealm(realm);
        } catch (IOException | JWSInputException e) {
            throw new FeignRequestException(HttpStatus.UNAUTHORIZED.getReasonPhrase(), HttpStatus.UNAUTHORIZED.value());
//            return null;
        }
        return keycloakUser;
    }

    @Override
    public JSONObject getUserInfoByUsername(String token,String username){
        KeycloakUser reqKeycloakUser = null;
        try {
            reqKeycloakUser = generateUser(token);
            JSONArray jsonArray=keycloakFeign.findUser(token, reqKeycloakUser.getRealm(), username);
            if(jsonArray !=null){
                JSONObject userObj=jsonArray.getJSONObject(0);
                KeycloakUser keycloakUser=new KeycloakUser();
                keycloakUser.setUsername(userObj.getString("username"));
                keycloakUser.setUserId(userObj.getString("id"));
                keycloakUser.setRealm(reqKeycloakUser.getRealm());
                return JsonUtil.getSuccessJsonObject(JSONObject.parseObject(JSON.toJSONString(keycloakUser)));
            }
            return JsonUtil.getSuccessJsonObject();
        } catch (FeignException fe){
            fe.printStackTrace();
            return KeycloakUtil.getMsg(fe);
        }catch (FeignRequestException fre){
            fre.printStackTrace();
            return JsonUtil.getFailJsonObject(KeycloakUtil.getMsg(fre));
        }catch (Exception e) {
            System.err.println(e.getMessage());
            System.err.println(e.toString());
            return JsonUtil.getFailJsonObject(e.getMessage());
        }
    }


    @Override
    public JSONObject getAvailableListByClientId(String userId, String clientId, String token) {
        KeycloakUser keycloakUser = null;
        try {
            keycloakUser = generateUser(token);
            List<AdminClientRole> responseList=keycloakFeign.available(token,keycloakUser.getRealm(),userId,clientId);
            return JsonUtil.getSuccessJsonObject(responseList);
        } catch (FeignException fe) {
            return KeycloakUtil.getMsg(fe);
        }
    }

    @Override
    public JSONObject getAllocatedListByClientId(String userId, String clientId, String token) {
        KeycloakUser keycloakUser = null;
        try {
            keycloakUser = generateUser(token);
            List<AdminClientRole> responseList=keycloakFeign.composite(token,keycloakUser.getRealm(),userId,clientId);
            return JsonUtil.getSuccessJsonObject(responseList);
        } catch (FeignException fe) {
            return KeycloakUtil.getMsg(fe);
        }
    }

    @Override
    public JSONObject allocateRoles(List<AdminClientRole> clientRoles,String userId, String clientId, String token) {
        if (StrUtil.isEmpty(userId)||StrUtil.isEmpty(clientId)) {
            return JsonUtil.getFailJsonObject(StateCode.ERROR_PARAMS_WRONGFUL.getMsg());
        }

        KeycloakUser keycloakUser = null;
        try {
            keycloakUser = generateUser(token);

            //先查询所有的客户端
            List<AdminClient> clientList=keycloakFeign.clients(token, keycloakUser.getRealm());
            for (AdminClient client : clientList) {
                if(client.getClientId().equals("realm-management")){
                    //查询可用的角色
                    List<AdminClientRole> clientRoleList=keycloakFeign.available(token,keycloakUser.getRealm(),userId,client.getId());
                    keycloakFeign.allocateRoles(token, keycloakUser.getRealm(),userId,client.getId(),clientRoleList);
                    break;
                }
            }
            keycloakFeign.allocateRoles(token, keycloakUser.getRealm(),userId,clientId,clientRoles);
            return JsonUtil.getSuccessJsonObject();
        } catch (FeignException fe) {
            return KeycloakUtil.getMsg(fe);
        }
    }

    @Override
    public JSONObject deleteRoles(List<AdminClientRole> clientRoles, String userId, String clientId, String token) {
        if (StrUtil.isEmpty(userId)||StrUtil.isEmpty(clientId)) {
            return JsonUtil.getFailJsonObject(StateCode.ERROR_PARAMS_WRONGFUL.getMsg());
        }

        KeycloakUser keycloakUser = null;
        try {
            keycloakUser = generateUser(token);
            keycloakFeign.deleteRoles(token, keycloakUser.getRealm(),userId,clientId,clientRoles);
            return JsonUtil.getSuccessJsonObject();
        } catch (FeignException fe) {
            return KeycloakUtil.getMsg(fe);
        }
    }
    @Override
    public JSONObject getListByClientId(String token,String clientId) {
        KeycloakUser keycloakUser = null;
        try {
            keycloakUser = generateUser(token);
            List<AdminClientRole> responseList=keycloakFeign.roles(token,keycloakUser.getRealm(),clientId);
            return JsonUtil.getSuccessJsonObject(responseList);
        } catch (FeignException fe) {
            return KeycloakUtil.getMsg(fe);
        }
    }

    @Override
    public JSONObject getAvailableClientList(String token) {
        if (StrUtil.isEmpty(token)) {
            return JsonUtil.getFailJsonObject(StateCode.ERROR_PARAMS_WRONGFUL.getMsg());
        }
        KeycloakUser user = null;
        try {
            user = generateUser(token);
            List<AdminClient> clientRepresentationList=keycloakFeign.clients(token, user.getRealm());
            return JsonUtil.getSuccessJsonObject(clientRepresentationList);
        } catch (FeignException fe) {
            return KeycloakUtil.getMsg(fe);
        }
    }




//    public boolean verifyToken(String token) {
//        String realm = "China";
//        String resource = "web_app";
//        String authServerUrl = "http://39.107.60.53:9080/auth";
//
//        AccessToken accessToken = null;
//        try {
//            //1、设置client配置信息
//            AdapterConfig adapterConfig = new AdapterConfig();
//            //realm name
//            adapterConfig.setRealm(realm);
//            //client_id
//            adapterConfig.setResource(resource);
//            //认证中心keycloak地址
//            adapterConfig.setAuthServerUrl(authServerUrl);
//            //访问https接口时，禁用证书检查。
//            adapterConfig.setDisableTrustManager(true);
//            //2、根据client配置信息构建KeycloakDeployment对象
//            KeycloakDeployment deployment = KeycloakDeploymentBuilder.build(adapterConfig);
//            //3、执行token签名验证和有效性检查（不通过会抛异常）
//            accessToken = AdapterTokenVerifier.verifyToken(token, deployment);
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//        if(accessToken!=null){
//            return true;
//        }else{
//            return false;
//        }
//    }

//    public static void main(String[] args) {
//        String token="bearer eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJfWjI1bTdiU0RWcVBubVU4YUlIcEo1dHAydUlYUTlSbFAzeVh6RElrT0trIn0.eyJqdGkiOiIxYmY1ZGNmMS02ZWViLTQ2NTctODYxNy0wN2Q4YjcxMTA4ZjUiLCJleHAiOjE2MjU3MjM2NDYsIm5iZiI6MCwiaWF0IjoxNjI1NjM3MjQ2LCJpc3MiOiJodHRwOi8vMzkuMTA3LjYwLjUzOjkwODAvYXV0aC9yZWFsbXMvY2hpbmEiLCJhdWQiOlsicmVhbG0tbWFuYWdlbWVudCIsImJyb2tlciIsImFjY291bnQiXSwic3ViIjoiM2MyM2Y5NWYtOTdlMi00MmNhLWI3ZWMtNDY4ZmFmZTFhMGE4IiwidHlwIjoiQmVhcmVyIiwiYXpwIjoid2ViX2FwcCIsImF1dGhfdGltZSI6MCwic2Vzc2lvbl9zdGF0ZSI6Ijk1NGQ0MmIzLWNjMjQtNDQxYS05ZDNhLWRkNzJjZTM3MDFmZSIsImFjciI6IjEiLCJyZWFsbV9hY2Nlc3MiOnsicm9sZXMiOlsib2ZmbGluZV9hY2Nlc3MiLCJ1bWFfYXV0aG9yaXphdGlvbiJdfSwicmVzb3VyY2VfYWNjZXNzIjp7InJlYWxtLW1hbmFnZW1lbnQiOnsicm9sZXMiOlsidmlldy1yZWFsbSIsInZpZXctaWRlbnRpdHktcHJvdmlkZXJzIiwibWFuYWdlLWlkZW50aXR5LXByb3ZpZGVycyIsImltcGVyc29uYXRpb24iLCJyZWFsbS1hZG1pbiIsImNyZWF0ZS1jbGllbnQiLCJtYW5hZ2UtdXNlcnMiLCJxdWVyeS1yZWFsbXMiLCJ2aWV3LWF1dGhvcml6YXRpb24iLCJxdWVyeS1jbGllbnRzIiwicXVlcnktdXNlcnMiLCJtYW5hZ2UtZXZlbnRzIiwibWFuYWdlLXJlYWxtIiwidmlldy1ldmVudHMiLCJ2aWV3LXVzZXJzIiwidmlldy1jbGllbnRzIiwibWFuYWdlLWF1dGhvcml6YXRpb24iLCJtYW5hZ2UtY2xpZW50cyIsInF1ZXJ5LWdyb3VwcyJdfSwid2ViX2FwcCI6eyJyb2xlcyI6WyLlt6XnqIvlt6Hmo4AiLCLmlofmoaPop4TojIMiLCLpobnnm67orr7nva5f5paw5aKeIiwi6K6-5aSH57G75Yir6K6-572uIiwi5qOA5rWL5Luq5ZmoIiwi5bel56iL5oql5ZGKIiwi572R57uc6LCD6K-VIiwi5bel56iL6LWE5paZIiwi5L-h5oGv6K6-572uIiwi5Zyw5Zu-55yL5p2_Iiwi57uE57uH5p625p6EIiwi5oql6K2m55-t5L-h5pel5b-XIiwi5oiQ5pys5qC4566XIiwi6KeE5YiZ6K6-572uIiwi5oql6K2m5L-h5oGvIiwi5bel56iL55uR5rWLIiwi6aG555uu6K6-572uX-S_ruaUuSIsIuacuuaehOi1hOi0qCIsIumhueebruWkh-ahiCIsIumhueebruiuvue9rl_mn6XnnIsiLCLmtYvngrnnsbvlnovorr7nva4iLCLmiqXorabnu5_orqEiLCLmlbDmja7nnIvmnb8iLCLpobnnm67nnIvmnb8iLCLpobnnm67otYTmlpkiLCLmtYvph4_ku6rlmagiLCLnvZHnu5zorr7lpIciLCLkvKDmhJ_lmagiXX0sImJyb2tlciI6eyJyb2xlcyI6WyJyZWFkLXRva2VuIl19LCJhY2NvdW50Ijp7InJvbGVzIjpbIm1hbmFnZS1hY2NvdW50IiwibWFuYWdlLWFjY291bnQtbGlua3MiLCJ2aWV3LXByb2ZpbGUiXX19LCJzY29wZSI6IiIsIm5hbWUiOiLotoXnuqfnrqHnkIblkZgiLCJwcmVmZXJyZWRfdXNlcm5hbWUiOiJzdXBlciIsImdpdmVuX25hbWUiOiLotoXnuqfnrqHnkIblkZgifQ.QnIJQPfavN0ej4_VF5p4xdtRqWnAYpwFlYh8QYS1GIFzdXHhgzds4l90m0LJUBobhNWYQMh5ODwOWr7x5N5IzSGzjbqBLr1nAbDmOQE5jaFfkQOSm_wcGnICzAAaJoPHOX5xi98L-k1p7BKmSeWQyJm8COfp1_klAIFJyz1J6uHFbVOjLmNwCZNznrTJPe9zAm34AHaIRcGh1ZIOizFNVx9DKyPe2gtRto_AU4nz7XdJlZLknBuCpGPQHYlLGe3tLr2AIOqskHnDa5lP4dDC0ia05ZY_pSn096xpkGUMkwl__Z4qtOknschDsOuzm3O6xmH2H9mw5TX6Mcui5Mfcwg";
//
//        verifyToken(token);
//    }

    @Override
    public JSONObject getUserInfo(String token,String keycloakId) {
        if (StrUtil.isEmpty(keycloakId)) {
            return JsonUtil.getFailJsonObject(StateCode.ERROR_PARAMS_WRONGFUL.getMsg());
        }
        KeycloakUser keycloakUser = null;
        try {
            keycloakUser = generateUser(token);
            final UserRepresentation userRepresentation= keycloakFeign.getUserInfo(token, keycloakUser.getRealm(), keycloakId);
            return JsonUtil.getSuccessJsonObject(userRepresentation);
        } catch (FeignException fe) {
            return KeycloakUtil.getMsg(fe);
        }
    }



    public JSONObject getResources(String authorization){
        KeycloakUser user = generateUser(authorization);
        ////通过用户获取配置的角色列表
        List<KeycloakRole> keycloakRoleList=getRolesByUsername(user.getUsername());
        List<String> roleIds=new ArrayList<>();
        for (KeycloakRole keycloakRole : keycloakRoleList) {
            roleIds.add(keycloakRole.getId());
        }
        //获取客户端web_client下所有角色和策略之间的关系
        List<PolicyConfig> policyConfigList=policyConfigMapper.getRolePolicyMapper(clienId);
        List<String> policyIds=new ArrayList<>();
        for (PolicyConfig policyConfig : policyConfigList) {
            String value=policyConfig.getValue();
            if(!StrUtil.isBlank(value)){
                JSONArray jsonArray=JSONArray.parseArray(value);
                for (Object o : jsonArray) {
                    JSONObject obj= (JSONObject) o;
                    String roleId=obj.getString("id");
                    if(roleIds.contains(roleId)){
                        policyIds.add(policyConfig.getPolicyId());
                    }
                }
            }
        }

        Map<String,Object> map=new HashMap<>();
        map.put("list",policyIds);
        //通过策略查找资源
        List<ResourcePolicy> resourcePolicyList=resourcePolicyMapper.getResourceIdsByPolicy(map);
        map.put("resourcePolicyList",resourcePolicyList);
        //获取资源详情
        List<ResourceExAttribute> resourceExAttributeList=resourceServerResourceMapper.getResourceByResourceIds(map);
        for (ResourceExAttribute resourceExAttribute : resourceExAttributeList) {
            List<ResourceAttribute> list=resourceExAttribute.getList();
            if(!CollectionUtils.isEmpty(list)){
                JSONObject jsonObject=new JSONObject();
                for (ResourceAttribute resourceAttribute : list) {
                    List<String> tmpList=new ArrayList<>();
                    tmpList.add(resourceAttribute.getValue());
                    jsonObject.put(resourceAttribute.getName(),tmpList);
                }
                resourceExAttribute.setAttributes(jsonObject);
            }
        }
        return JsonUtil.getSuccessJsonObject(resourceExAttributeList);
    }

    public JSONObject getAllResources(){
        ////通过用户获取配置的角色列表
        List<KeycloakRole> keycloakRoleList=getAllRoles();
        List<String> roleIds=new ArrayList<>();
        for (KeycloakRole keycloakRole : keycloakRoleList) {
            roleIds.add(keycloakRole.getId());
        }
        //获取客户端web_client下所有角色和策略之间的关系
        List<PolicyConfig> policyConfigList=policyConfigMapper.getRolePolicyMapper(clienId);
        List<String> policyIds=new ArrayList<>();
        for (PolicyConfig policyConfig : policyConfigList) {
            String value=policyConfig.getValue();
            if(!StrUtil.isBlank(value)){
                JSONArray jsonArray=JSONArray.parseArray(value);
                for (Object o : jsonArray) {
                    JSONObject obj= (JSONObject) o;
                    String roleId=obj.getString("id");
                    if(roleIds.contains(roleId)){
                        policyIds.add(policyConfig.getPolicyId());
                    }
                }
            }
        }

        Map<String,Object> map=new HashMap<>();
        map.put("list",policyIds);
        //通过策略查找资源
        List<ResourcePolicy> resourcePolicyList=resourcePolicyMapper.getResourceIdsByPolicy(map);
        map.put("resourcePolicyList",resourcePolicyList);
        //获取资源详情
        List<ResourceExAttribute> resourceExAttributeList=resourceServerResourceMapper.getResourceByResourceIds(map);
        for (ResourceExAttribute resourceExAttribute : resourceExAttributeList) {
            List<ResourceAttribute> list=resourceExAttribute.getList();
            if(!CollectionUtils.isEmpty(list)){
                JSONObject jsonObject=new JSONObject();
                for (ResourceAttribute resourceAttribute : list) {
                    List<String> tmpList=new ArrayList<>();
                    tmpList.add(resourceAttribute.getValue());
                    jsonObject.put(resourceAttribute.getName(),tmpList);
                }
                resourceExAttribute.setAttributes(jsonObject);
            }
        }
        return JsonUtil.getSuccessJsonObject(resourceExAttributeList);
    }




    //mapper对接
    @Override
    public List<KeycloakRole> getRolesByUsername(String username){
        Map<String,Object> map=new HashMap<>();
        map.put("username",username);
        map.put("client",clienId);
        List<KeycloakRole> keycloakRoleList= keycloakRoleMapper.getRolesByUsername(map);
        return keycloakRoleList;
    }

    @Override
    public List<KeycloakRole> getAllRoles(){
        Map<String,Object> map=new HashMap<>();
        map.put("realm",realm);
        map.put("client",clienId);
        List<KeycloakRole> keycloakRoleList= keycloakRoleMapper.getAllRoles(map);
        return keycloakRoleList;
    }


    @Override
    public Boolean isAccessToken(String Authorization, User user) {
        JSONObject jsonObject=getUserInfo(Authorization,user.getKeycloakId());
        if(jsonObject.getIntValue("code")==0){
            //查看redis里面的token是否有效

            TokenInfo tokenInfo = (TokenInfo) redisService.getValue(UserConstant.tokenUserMap);
            if(tokenInfo==null){
                return false;
            }else{
                if(tokenInfo.getToken().equals(Authorization)) {
                    return true;
                }else{
                    return false;
                }
            }
        }else{
            return false;
        }
    }
}
